package com.moon.app;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.moon.R;
import com.moon.common.AbstractActivity;
import com.moon.constants.MoonConstants;

/**
 * 找回密码
 * 
 * @author paul
 * @date 2014年5月3日
 */
public class FindPasswordActivity extends AbstractActivity {

    private static final String TAG = FindPasswordActivity.class.getSimpleName();

    private EditText            email;

    private BootstrapButton     findPasswordBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_password);

        email = (EditText) findViewById(R.id.editLoginAccount);
        findPasswordBtn = (BootstrapButton) findViewById(R.id.buttonFindPassword);
        findPasswordBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Pattern.matches(
                        "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$",
                        email.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "邮箱格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                //找回密码
                findPasswordVolley();

            }
        });

    }

    private boolean findPasswordVolley() {
        String findUrl = "/mobile_user/dofind.do";
        try {
            RequestQueue mRequestQueue = Volley.newRequestQueue(this);
            //ProgressDialog pd = ProgressDialog.show(this, "Please Wait...", "Please Wait...");
            //组装JsonObjectRequest
            JsonObjectRequest jr = getRequest(findUrl);
            //加入request队列
            mRequestQueue.add(jr);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "ERROR", e);
            return false;
        }

    }

    /**
     * @param findUrl
     * @return
     * @throws JSONException
     */
    private JsonObjectRequest getRequest(String findUrl) throws JSONException {
        //组装JsonObjectRequest

        Map<String, String> map = new HashMap<String, String>();
        map.put("email", email.getText().toString());
        //        final JSONObject jsonRequest = new JSONObject();
        //        jsonRequest.put("email", email.getText().toString());
        //jsonRequest.put("email", email.getText().toString());

        // POST提交后台始终拿不到参数
        //
        JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET, MoonConstants.MOON_DOMAIN
                + findUrl + "?email=" + email.getText().toString(), null,
                new Response.Listener<JSONObject>() {
                    //但是,匿名内部类里又有匿名内部类,导致里层的打不到断点
                    //JsonObjectRequest 是一层, Listener又是一层
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            if (response.getBoolean("success")) {
                                Toast.makeText(getApplicationContext(), "验证码已发送您邮箱",
                                        Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(FindPasswordActivity.this,
                                        ResetPasswordActivity.class);
                                intent.putExtra(MoonConstants.USER_EMAIL, email.getText().toString());
                                startActivity(intent);
                            } else {
                                Toast.makeText(getApplicationContext(), "邮件发送失败,请稍后再尝试发送",
                                        Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            Toast.makeText(getApplicationContext(), "邮件发送失败,请稍后再尝试发送",
                                    Toast.LENGTH_SHORT).show();
                            Log.e(TAG, "sendmaill error,", e);
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "邮件发送失败,请稍后再尝试发送",
                                Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "sendmaill error,", error);
                    }
                }) {
            //各类重载

            @Override
            public RetryPolicy getRetryPolicy() {
                //默认会重试一次, 阻止重试
                DefaultRetryPolicy policy = new DefaultRetryPolicy(
                        DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, 0,
                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                return policy;
            }

            //            @Override
            //            protected Map<String, String> getParams() throws AuthFailureError {
            //                Map<String, String> params = new HashMap<String, String>();
            //                params.put("email", email.getText().toString());
            //                return params;
            //            }
            //            
            //            @Override
            //            public Map<String, String> getHeaders() throws AuthFailureError {
            //                HashMap<String, String> headers = new HashMap<String, String>();
            //                headers.put("Accept", "application/json");
            //                headers.put("Content-Type","application/json; charset=UTF-8");
            //                return headers;
            //            }

            //            @Override  
            //            public byte[] getBody() 
            //            {  
            //                String str = "{'email':'ymkyve501@163.com'}";
            //                    return str == null ? super.getBody() : str.getBytes();  
            //            }  
        };
        //默认会重试一次, 阻止重试
        //        DefaultRetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
        //                0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        //        jr.setRetryPolicy(policy);
        return jr;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
